import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import * as dotenv from 'dotenv';
import * as path from 'path';
import * as fs from 'fs';

// 确保在数据库配置之前加载环境变量
const possiblePaths = [
  path.join(__dirname, '..', '..', '.env'),           // 从 config 目录到根目录
  path.join(process.cwd(), '.env'),                   // 当前工作目录
];

let envLoaded = false;
for (const envPath of possiblePaths) {
  if (fs.existsSync(envPath)) {
    dotenv.config({ path: envPath });
    console.log('📄 Database Config: Loaded .env from:', envPath);
    envLoaded = true;
    break;
  }
}

if (!envLoaded) {
  console.log('⚠️  Database Config: No .env file found, using system environment variables');
}

console.log('🔧 Database Config - Environment Variables:');
console.log('   NODE_ENV:', process.env.NODE_ENV || 'NOT SET');
console.log('   DB_HOST:', process.env.DB_HOST || 'NOT SET');
console.log('   DB_PORT:', process.env.DB_PORT || 'NOT SET');
console.log('   DB_USERNAME:', process.env.DB_USERNAME || 'NOT SET');
console.log('   DB_PASSWORD:', process.env.DB_PASSWORD ? '***SET***' : 'NOT SET');
console.log('   DB_DATABASE:', process.env.DB_DATABASE || 'NOT SET');
console.log('   Current working directory:', process.cwd());

export const databaseConfig: TypeOrmModuleOptions = {
  type: 'mysql',
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT) || 3306,
  username: process.env.DB_USERNAME || 'root',
  password: process.env.DB_PASSWORD || 'password',
  database: process.env.DB_DATABASE || 'text_tags_db',
  entities: [__dirname + '/../**/*.entity{.ts,.js}'],
  synchronize: process.env.NODE_ENV !== 'production',
  logging: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn', 'info', 'log', 'schema'] : false,
  logger: process.env.NODE_ENV === 'development' ? 'advanced-console' : undefined,
  // 连接配置优化
  connectTimeout: 30000,        // 连接超时 30 秒
  acquireTimeout: 30000,        // 获取连接超时 30 秒
  retryAttempts: 5,             // 重试次数增加到 5 次
  retryDelay: 5000,            // 重试延迟 5 秒
  // 连接池配置优化
  extra: {
    connectionLimit: 5,          // 减少连接池大小
    acquireTimeout: 30000,      // 获取连接超时
    reconnect: true,            // 启用自动重连
    keepAlive: true,            // 保持连接活跃
    keepAliveInitialDelay: 0,   // 立即开始保持活跃
  },
};